<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\Teachers;
use App\Models\TeacherGroups;
use Illuminate\Support\Facades\DB;

class TeacherController extends Controller
{
    public function index(){
        $teachers = DB::table('teachers as t')
            ->join('teacher_groups as g', 't.group_id', '=', 'g.id')
            ->select('*', 'g.name as group_name', 't.name as teacher_name')
            ->orderBy('status', 'desc')
            ->paginate(config('constants.page_num'));
        return view('admin.teacher.index', compact('teachers'));
    }

    public function create(){
        $groups = TeacherGroups::get();
        return view('admin.teacher.create', compact('groups'));
    }

    public function store(Requests\CreateTeacherRequest $request){
        $data = $request->all();
        $result = Teachers::create($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/teacher')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function edit($teacher_id){
        $teacher = Teachers::findOrFail($teacher_id);
        $groups = TeacherGroups::get();
        return view('admin.teacher.edit', compact('teacher', 'groups'));
    }

    public function update(Requests\CreateTeacherRequest $request, $id){
        $teacher = Teachers::findOrFail($id);
        $data = $request->all();
        $result = $teacher->update($data);
        if ($result){
            exit(json_encode(array('code'=>1, 'url'=>'/admin/teacher')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy($id){
        $teacher = Teachers::findOrFail($id);
        $teacher->status = $teacher->status ? 0 : 1;
        if ($teacher->save()){
            exit(json_encode(array('code'=>1)));
        } else {
            exit(json_encode(array('code'=>0)));
        }
    }

    public function findTeacher(){
        $courseArr = Teachers::get()->toArray();
        foreach ($courseArr as $value){
            $result[] = array(
                'value' => $value['nice_name'],
                'id'    => $value['teacher_id'],
            );
        }
        return json_encode($result);
    }
}
